<?php
/**
 * Created by PhpStorm.
 * User: yzg
 * Date: 2016/1/19
 * Time: 15:36
 */

class Weixin_vote_model extends CI_Model
{
    public $table;
    public function __construct()
    {
        parent::__construct();
        $this->table = 'vote';
        $this->tablelog = 'votelog';
    }

    public function remove_all($id){
        if($this->remove_row(array('id' => $id))){
            $where = $this->set_where(array('vid'=>$id));
            $this->db->where($where, NULL, FALSE);
            return $this->db->delete($this->tablelog);
        }
    }

    /**
     * 添加数据
     * @param $data
     * @return bool
     */
    function add_row($data){
        if(is_array($data)){
            if(!$data['sid']){
                $data['sid'] = SITEID;
            }
            if($this->db->insert($this->table,$data)){
                return $this->db->insert_id();
            }else{
                return false;
            }
        }
    }
    /**
     *
     * 更新数据
     * @param array $data 数据数组
     * @param array $where 更新条件
     */
    function edit_row($data,$where){
        $table = $this->table;
        if(!empty($where))$this->db->where($where, NULL, FALSE);
        return $this->db->update($table,$data);
    }
    /**
     *
     * 删除数据
     * @param array $where 删除条件
     */
    function remove_row($where=array()){
        $where = $this->set_where($where);
        $this->db->where($where, NULL, FALSE);
        return $this->db->delete($this->table);
    }

    /**
     * 查询单条记录
     * @param mixed $where 查询条件 array|string
     * @param string $field 获取到的字段
     * @return mixed 返回数据
     */
    public function get_row($where,$field=''){
        $table = $this->table;
        if(!empty($where)) $this->db->where($where);
        if(!empty($field)) $this->db->select($field);
        $query = $this->db->get($table,1);
        return $query->row_array();
    }

    /**
     * 查询多条记录
     * @param mixed $where 查询条件 array|string
     * @param string $field 获取到的字段
     * @return mixed 返回数据
     */
    public function get_rows($where,$field=''){
        $table = $this->table;
        if(!empty($where)) $this->db->where($where);
        if(!empty($field)) $this->db->select($field);
        $query = $this->db->get($table);
        return $query->result_array();
    }

    /**
     * 返回查询条件
     * @param $where 查询条件
     * @return array|string
     */
    function set_where($where){
        if(is_array($where))$where['sid']=SITEID;
        else $where=$where?$where.' AND sid='. SITEID:'sid='.SITEID;
        return $where;
    }

}